/*
 * @Author: ZhanXie
 * @Date: 2020-09-01 20:59:04
 * @LastEditors: ZhanXie
 * @LastEditTime: 2020-09-01 22:04:22
 * @Description: json schema 验证中间件
 * @FilePath: /weibo/src/middlewares/validator.js
 */

const { ErrorModel } = require('../model/ResModel')
const { jsonSchemaFileInfo } = require('../model/ErrorInfo')

/**
  *  生成 json schema 验证中间件
  * @param {function} validateFn 验证函数 
  */
function genValidator(validateFn) {
  async function validator(ctx, next) {
    const data = ctx.request.body
    const error = validateFn(data)
    if (error) {
      // 验证失败
      ctx.body = new ErrorModel(jsonSchemaFileInfo)
      return
    }
    // 验证成功，继续
    await next()
  }

  return validator
}

module.exports = {
  genValidator
}